<template>
    <div class="compare-page">
        <!-- 顶部 Header -->
        <header class="compare-header">
            <el-button type="text" :icon="ArrowLeft" @click="goBack">返回</el-button>
            <div class="header-right">
                <span class="similarity">
                    文本相似度：
                    <b class="similarity-badge">{{ similarity }}%</b>
                </span>
                <!-- <div class="connection-controls">
                     <span class="connection-control-title">连线调整:</span>
                     <div class="connection-control-buttons">
                         <el-button size="small" @click="adjustConnectionOffset('left', -5)" title="左侧连接点向左移动">←L</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('left', 5)" title="左侧连接点向右移动">L→</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', -5)" title="右侧连接点向左移动">←R</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', 5)" title="右侧连接点向右移动">R→</el-button>
                         <el-button size="small" type="info" @click="resetConnectionOffset()" title="重置连线位置">重置</el-button>
                     </div>
                 </div> -->
                <el-button type="primary" :icon="Reading" @click="showDiffPoint">差异点</el-button>
            </div>
        </header>

        <!-- 中部 PDF 对比区 + 差异列表 -->
        <div class="compare-main" :class="{ 'with-diff-list': showDiffList }">
            <div class="pdf-compare-content">
                <!-- 左侧PDF控制面板 -->
                <div class="pdf-container">
                    <div class="control-panel">
                        <div class="zoom-controls">
                            <el-button-group>
                                <el-button :icon="ZoomIn" @click="zoomIn(1)" size="small" title="放大"></el-button>
                                <el-button :icon="ZoomOut" @click="zoomOut(1)" size="small" title="缩小"></el-button>
                                <el-button :icon="Refresh" @click="resetZoom(1)" size="small" title="重置"></el-button>
                            </el-button-group>
                            <span class="zoom-level">{{ Math.round(zoomLevels.left * 100) }}%</span>
                        </div>
                        <div class="page-controls">
                            <el-button size="small" :icon="ArrowUp" @click="prevPage()" 
                                :disabled="page1 <= 1" title="上一页" circle />
                            <span class="page-display">{{ page1 }}/{{ pdf1TotalPages }}</span>
                            <el-button size="small" :icon="ArrowDown" @click="nextPage()" 
                                :disabled="page1 >= pdf1TotalPages" title="下一页" circle />
                        </div>
                    </div>
                    <div class="pdf-viewer" ref="leftPdfViewer">
                        <canvas ref="pdfCanvas" class="pdf-canvas pdf-canvas-full"></canvas>
                    </div>
                </div>
                <!-- <div class="page-control-panel">
                    <div class="footer-page footer-page-center" :style="{
                        position: 'absolute',
                        top: '45px',
                        left: '50%',
                        transform: 'translate(-50%, -100%)',
                        zIndex: 10
                    }">
                        <span class="page-current">{{ page1 }}</span>
                        <span class="page-sep">/</span>
                        <span class="page-total">{{ pdf1TotalPages }}</span>
                    </div>
                    <div class="page-control-btns mt-1">
                        <el-button size="default" :icon="ArrowLeft" @click="prevPage" class="page-arrow-btn"
                            :disabled="page1 <= 1 || page2 <= 1" />
                        <el-button size="default" :icon="ArrowRight" @click="nextPage" class="page-arrow-btn"
                            :disabled="page1 >= pdf1TotalPages || page2 >= pdf2TotalPages">
                        </el-button>
                    </div>
                </div> -->
                <!-- 右侧PDF控制面板 -->
                <div class="pdf-container">
                    <div class="control-panel">
                        <div class="zoom-controls">
                            <el-button-group>
                                <el-button :icon="ZoomIn" @click="zoomIn(2)" size="small" title="放大"></el-button>
                                <el-button :icon="ZoomOut" @click="zoomOut(2)" size="small" title="缩小"></el-button>
                                <el-button :icon="Refresh" @click="resetZoom(2)" size="small" title="重置"></el-button>
                            </el-button-group>
                            <span class="zoom-level">{{ Math.round(zoomLevels.right * 100) }}%</span>
                        </div>
                        <div class="page-controls">
                            <el-button size="small" :icon="ArrowUp" @click="prevPage()" 
                                :disabled="page2 <= 1" title="上一页" circle />
                            <span class="page-display">{{ page2 }}/{{ pdf2TotalPages }}</span>
                            <el-button size="small" :icon="ArrowDown" @click="nextPage()" 
                                :disabled="page2 >= pdf2TotalPages" title="下一页" circle />
                        </div>
                    </div>
                    <div class="pdf-viewer" ref="rightPdfViewer">
                        <canvas ref="pdfCanvas2" class="pdf-canvas pdf-canvas-full"></canvas>
                    </div>
                </div>

                <!-- 差异列表 - 改为内嵌式布局 -->
                <div v-if="showDiffList" class="diff-list-sidebar">
                    <div class="diff-list-header">
                        <h3>差异列表</h3>
                        <el-button :icon="Close" @click="showDiffList = false" size="small" circle></el-button>
                    </div>
                    <div class="diff-list-content">
                        <div v-for="(item, idx) in diffList" :key="idx" class="diff-item diff-item-hover"
                            @click="highlightDiff(idx)">
                            <div class="diff-title">{{ item.type }}<span class="diff-label">（第{{ item.pageNumber }}页）</span></div>
                            <div class="diff-row">
                                <span class="diff-label">左：</span>
                                <span class="text-red-500">{{ item.details.text.document1 }}</span>
                            </div>
                            <div class="diff-row">
                                <span class="diff-label">右：</span>
                                <span class="text-white">{{ item.details.text.document2 }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部 文件名和翻页 -->
        <footer class="compare-footer" :class="{ 'with-diff-list': showDiffList }">
            <div class="footer-block">
                <span class="footer-filename">{{ pdf1Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page1 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf1TotalPages }}</span>
                </span>
            </div>
            <div class="footer-block">
                <span class="footer-filename">{{ pdf2Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page2 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf2TotalPages }}</span>
                </span>
            </div>
        </footer>
    </div>
</template>

<script setup>

import {  Reading, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, ZoomIn, ZoomOut, Refresh, Close } from '@element-plus/icons-vue'
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import { ElLoading } from 'element-plus'
import * as pdfjsLib from 'pdfjs-dist/build/pdf.min.mjs'

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
).toString()


import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute();
console.log(`route.params.res`, route.params); // 0


const similarity = ref(87)
const pdf1Url = ref('')
const pdf2Url = ref('')
const pdf1Name = '原文稿'
const pdf2Name = '对比文稿'
const page1 = ref(1)
const page2 = ref(1)
const pdf1TotalPages = ref(1)
const pdf2TotalPages = ref(1)
const showDiffList = ref(false)

const pdfCanvas = ref(null)
const pdfCanvas2 = ref(null)

let pdf1Instance = null
let pdf2Instance = null
let pdf1RenderPromise = Promise.resolve();
let pdf2RenderPromise = Promise.resolve();

const diffList = ref([]) // 初始为空
// 缩放控制相关
const zoomLevels = ref({
    left: 1.25,
    right: 1.25
})
const defaultZoom = 1.25
const minZoom = 0.5
const maxZoom = 3.0
const zoomStep = 0.25
// 连线位置偏移量 - 设置初始值使连线准确连接到文字差异
// 左侧文档连接点在右边界，右侧文档连接点在左边界
const connectionOffset = ref({ left: 5, right: -5 })
const isRendering1 = ref(false) // 防止重复渲染的标志
const isRendering2 = ref(false) // 防止重复渲染的标志

// 鼠标拖动相关变量
const isDragging1 = ref(false)
const isDragging2 = ref(false)
const startX1 = ref(0)
const startY1 = ref(0)
const scrollLeft1 = ref(0)
const scrollTop1 = ref(0)
const startX2 = ref(0)
const startY2 = ref(0)
const scrollLeft2 = ref(0)
const scrollTop2 = ref(0)

let loading = null;

/**
 * 调整连线偏移量
 * @param {string} side 'left' 或 'right'
 * @param {number} value 偏移量增减值
 */
function adjustConnectionOffset(side, value) {
    if (side === 'left') {
        connectionOffset.value.left += value;
    } else {
        connectionOffset.value.right += value;
    }
    console.log(`当前连线偏移量: 左侧=${connectionOffset.value.left}, 右侧=${connectionOffset.value.right}`);
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

/**
 * 重置连线偏移量到默认值
 */
function resetConnectionOffset() {
    // 根据屏幕宽度自动调整偏移量
    autoAdjustConnectionOffset();
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

// 在翻页后自动高亮
watch([page1, page2], () => {
    // highlightDiffsForCurrentPage();
});

const showDiffPoint = () => {
    showDiffList.value = !showDiffList.value
}



// 修改loadAndRenderPdf，支持缓存pdf实例
async function loadAndRenderPdf(pageNum = 1, zoom = null) {
    if (!pdf1Instance || isRendering1.value) return;
    isRendering1.value = true;
    try {
        await pdf1RenderPromise;
        
        // 使用传入的zoom或当前zoomLevels.left
        const actualZoom = zoom !== null ? zoom : zoomLevels.value.left;
        
        const page = await pdf1Instance.getPage(pageNum);
        const dpr = window.devicePixelRatio || 1;
        const viewport = page.getViewport({ scale: actualZoom });
        const canvas = pdfCanvas.value;
        const context = canvas.getContext('2d');
        canvas.width = viewport.width * dpr;
        canvas.height = viewport.height * dpr;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;
        context.setTransform(dpr, 0, 0, dpr, 0, 0);
        pdf1RenderPromise = page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        await pdf1RenderPromise;
    } finally {
        isRendering1.value = false;
    }
}

// 右侧PDF渲染，缓存pdf实例
async function loadAndRenderPdf2(pageNum = 1, zoom = null) {
    if (!pdf2Instance || isRendering2.value) return;
    isRendering2.value = true;
    try {
        await pdf2RenderPromise;
        
        // 使用传入的zoom或当前zoomLevels.right
        const actualZoom = zoom !== null ? zoom : zoomLevels.value.right;
        
        const page = await pdf2Instance.getPage(pageNum);
        const dpr = window.devicePixelRatio || 1;
        const viewport = page.getViewport({ scale: actualZoom });
        const canvas = pdfCanvas2.value;
        const context = canvas.getContext('2d');
        canvas.width = viewport.width * dpr;
        canvas.height = viewport.height * dpr;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;
        context.setTransform(dpr, 0, 0, dpr, 0, 0);
        pdf2RenderPromise = page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        await pdf2RenderPromise;
    } finally {
        isRendering2.value = false;
    }
}

// 缩放控制函数
async function zoomIn(pdfSide) {
    if (pdfSide === 1) {
        if (zoomLevels.value.left < maxZoom) {
            zoomLevels.value.left = Math.min(zoomLevels.value.left + zoomStep, maxZoom);
            await loadAndRenderPdf(page1.value, zoomLevels.value.left);
        }
    } else {
        if (zoomLevels.value.right < maxZoom) {
            zoomLevels.value.right = Math.min(zoomLevels.value.right + zoomStep, maxZoom);
            await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
        }
    }
}

async function zoomOut(pdfSide) {
    if (pdfSide === 1) {
        if (zoomLevels.value.left > minZoom) {
            zoomLevels.value.left = Math.max(zoomLevels.value.left - zoomStep, minZoom);
            await loadAndRenderPdf(page1.value, zoomLevels.value.left);
        }
    } else {
        if (zoomLevels.value.right > minZoom) {
            zoomLevels.value.right = Math.max(zoomLevels.value.right - zoomStep, minZoom);
            await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
        }
    }
}

async function resetZoom(pdfSide) {
    if (pdfSide === 1) {
        zoomLevels.value.left = defaultZoom;
        await loadAndRenderPdf(page1.value, zoomLevels.value.left);
    } else {
        zoomLevels.value.right = defaultZoom;
        await loadAndRenderPdf2(page2.value, zoomLevels.value.right);
    }
}

// 翻页按钮事件
function prevPage() {
    clearDiffLine(); // 翻页前清除连线
    if (page1.value > 1) {
        page1.value--
        loadAndRenderPdf(page1.value)
    }
    if (page2.value > 1) {
        page2.value--
        loadAndRenderPdf2(page2.value)
    }
}

function nextPage() {
    clearDiffLine(); // 翻页前清除连线
    if (page1.value < pdf1TotalPages.value) {
        page1.value++
        loadAndRenderPdf(page1.value)
    }
    if (page2.value < pdf2TotalPages.value) {
        page2.value++
        loadAndRenderPdf2(page2.value)
    }
}




function goBack() {
    // clearDiffLine(); // 离开页面前清除连线
    router.push('/home')
}

// 清除差异连线
function clearDiffLine() {
    const lineCanvas = document.getElementById('diff-line-canvas');
    if (lineCanvas) {
        lineCanvas.getContext('2d').clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    }
}


let currentDiffIdx = null;
async function highlightDiff(idx) {
    currentDiffIdx = idx;
    const diff = diffList.value[idx];

    // 1. 获取页码信息
    const leftPage = diff.pageNumber || 1;
    const rightPage = diff.pageNumber || 1;

    // 2. 翻页（如果需要），并等待渲染
    if (page1.value !== leftPage) {
        await loadAndRenderPdf(leftPage);
        page1.value = leftPage;
    }
    if (page2.value !== rightPage) {
        await loadAndRenderPdf2(rightPage);
        page2.value = rightPage;
    }

    // 3. 使用JSON中的rectangleDoc1和rectangleDoc2坐标数据
    // let leftHighlight = null;
    // let rightHighlight = null;
    
    // if (diff.details.rectangleDoc1) {
    //     const rect1 = diff.details.rectangleDoc1;
    //     // 调整y坐标计算，确保更准确地定位到文字位置
    //     // PDF坐标系（左下角为原点）转换为Canvas坐标系（左上角为原点）
    //     // 计算更精确的y坐标，考虑到PDF文字通常在矩形框的下部
    //     // 对于中文字符，通常基线位置更接近矩形框的下部
    //     // 根据实际测试结果调整偏移量
    //     const yOffset = rect1.height * 0.3; // 增加偏移量，使连线更接近文字中心
    //     leftHighlight = {
    //         pixelHeight: rect1.pixelHeight,
    //         pixelX: rect1.pixelX,
    //         pixelWidth: rect1.pixelWidth,
    //         pixelPageHeight: rect1.pixelPageHeight,
    //         pageHeight: rect1.pageHeight,
    //         pixelY: rect1.pixelY,
    //         x: rect1.x,
    //         y: rect1.pageHeight - rect1.y - rect1.height + yOffset, // 基本转换后向上偏移
    //         width: rect1.width,
    //         height: rect1.height,
    //         scale: 1.5,
    //         viewportHeight: rect1.pageHeight,
    //         originalY: rect1.y, // 保存原始y坐标，用于调试
    //         originalHeight: rect1.height, // 保存原始高度，用于调试
    //         yOffset: yOffset // 保存y偏移量，用于调试
    //     };
    // }
    
    // if (diff.details.rectangleDoc2) {
    //     const rect2 = diff.details.rectangleDoc2;
    //     // 调整y坐标计算，确保更准确地定位到文字位置
    //     // PDF坐标系（左下角为原点）转换为Canvas坐标系（左上角为原点）
    //     // 计算更精确的y坐标，考虑到PDF文字通常在矩形框的下部
    //     // 对于中文字符，通常基线位置更接近矩形框的下部
    //     // 根据实际测试结果调整偏移量
    //     const yOffset = rect2.height * 0.3; // 增加偏移量，使连线更接近文字中心
    //     rightHighlight = {
    //         pixelHeight: rect2.pixelHeight,
    //         pixelX: rect2.pixelX,
    //         pixelWidth: rect2.pixelWidth,
    //         pixelPageHeight: rect2.pixelPageHeight,
    //         pageHeight: rect2.pageHeight,
    //         pixelY: rect2.pixelY,
    //         x: rect2.x,
    //         y: rect2.pageHeight - rect2.y - rect2.height + yOffset, // 基本转换后向上偏移
    //         width: rect2.width,
    //         height: rect2.height,
    //         scale: 1.5,
    //         viewportHeight: rect2.pageHeight,
    //         originalY: rect2.y, // 保存原始y坐标，用于调试
    //         originalHeight: rect2.height, // 保存原始高度，用于调试
    //         yOffset: yOffset // 保存y偏移量，用于调试
    //     };
    // }

    // if ((leftHighlight && leftHighlight.x != null) || (rightHighlight && rightHighlight.x != null)) {
    //     // 输出调试信息，帮助分析连线位置
    //     console.log('高亮区域信息:', {
    //         left: leftHighlight,
    //         right: rightHighlight
    //     });
        
    //     // 4. 画连线
    //     setTimeout(() => {
    //         drawDiffLine(leftHighlight, rightHighlight);
    //         // 输出连线后的调试信息
    //         console.log('连线已绘制，当前差异索引:', idx);
    //     }, 100);
    // } else {
    //     // 清除连线
    //     const lineCanvas = document.getElementById('diff-line-canvas');
    //     if (lineCanvas) lineCanvas.getContext('2d').clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    // }
}

/**
 * 根据传入的 x, y, width, height 参数，对左右两个差异文本进行连线处理，中间用一个小方块图标连接
 * @param {Object} leftHighlight {x, y, width, height, scale, viewportHeight} 左侧高亮区域参数
 * @param {Object} rightHighlight {x, y, width, height, scale, viewportHeight} 右侧高亮区域参数
 */
function drawDiffLine(leftHighlight, rightHighlight) {
    // 创建或获取画布
    let lineCanvas = document.getElementById('diff-line-canvas');
    if (!lineCanvas) {
        lineCanvas = document.createElement('canvas');
        lineCanvas.id = 'diff-line-canvas';
        lineCanvas.style.position = 'fixed';
        lineCanvas.style.left = '0';
        lineCanvas.style.top = '0';
        lineCanvas.style.pointerEvents = 'none';
        lineCanvas.style.zIndex = 9;
        document.body.appendChild(lineCanvas);
    }
    
    // 设置画布尺寸
    lineCanvas.width = window.innerWidth;
    lineCanvas.height = window.innerHeight;
    const ctx = lineCanvas.getContext('2d');
    ctx.clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    
    // 获取左右PDF画布位置
    const leftCanvas = pdfCanvas.value;
    const rightCanvas = pdfCanvas2.value;
    const leftRect = leftCanvas?.getBoundingClientRect();
    const rightRect = rightCanvas?.getBoundingClientRect();
    
    // 计算连接点
    const leftPoint = convertPdfToScreenCoords(leftHighlight, leftRect, 'left');
    const rightPoint = convertPdfToScreenCoords(rightHighlight, rightRect, 'right');
    
    if (leftPoint && rightPoint) {
        // 绘制连线
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(64, 158, 255, 0.8)';
        ctx.lineWidth = 2;
        ctx.shadowColor = 'rgba(64, 158, 255, 0.4)';
        ctx.shadowBlur = 6;
        
        // 添加调试点
        ctx.fillStyle = 'red';
        ctx.beginPath();
        ctx.arc(leftPoint.x, leftPoint.y, 3, 0, Math.PI * 2);
        ctx.fill();
        ctx.beginPath();
        ctx.arc(rightPoint.x, rightPoint.y, 3, 0, Math.PI * 2);
        ctx.fill();
        
        // 绘制贝塞尔曲线
        ctx.beginPath();
        ctx.moveTo(leftPoint.x, leftPoint.y);
        
        // 调整贝塞尔曲线控制点
        const horizontalDistance = rightPoint.x - leftPoint.x;
        const controlDistance = Math.min(horizontalDistance * 0.3, 100); // 限制最大偏移
        
        ctx.bezierCurveTo(
            leftPoint.x + controlDistance,
            leftPoint.y,
            rightPoint.x - controlDistance,
            rightPoint.y,
            rightPoint.x,
            rightPoint.y
        );
        ctx.stroke();
    }
}

function convertPdfToScreenCoords(pdfCoords, canvasRect, side = 'left') {
    if (!pdfCoords || !canvasRect) return null;
    
    // 获取PDF容器的滚动位置
    const pdfViewer = side === 'left' ? 
        document.querySelector('.pdf-viewer:first-child') : 
        document.querySelector('.pdf-viewer:last-child');
    const scrollTop = pdfViewer?.scrollTop || 0;
    
    // 考虑设备像素比
    const dpr = window.devicePixelRatio || 1;
    
    // 使用PDF原始坐标
    const x = pdfCoords.x * dpr;
    const y = pdfCoords.y * dpr;
    
    // 计算实际屏幕位置，考虑滚动位置
    const screenX = canvasRect.left + x;
    const screenY = canvasRect.top + y - scrollTop;

    
    let connectionPoint = {
        x: screenX,
        y: screenY + (pdfCoords.height * dpr / 2) // 取文本高度中点
    };
    
    // 根据左右位置调整连接点
    if (side === 'left') {
        connectionPoint.x = screenX + (pdfCoords.width * dpr) + connectionOffset.value.left;
    } else {
        connectionPoint.x = screenX + connectionOffset.value.right;
    }
    
    return connectionPoint;
}

onMounted(async () => {
    loading = ElLoading.service({
        lock: true,
        text: '加载中，请稍后',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let result = JSON.parse(localStorage.getItem('res'));
    pdf1Url.value = result.generatedFiles[0];
    pdf2Url.value = result.generatedFiles[1];

    diffList.value = result.differences; // 从结果中获取差异列表

    similarity.value = 100 - result.totalDifferences || 0; // 获取相似度

    // pdf1Name.value = result.nameInfo.name1 || '比对文档1';
    // pdf2Name.value = result.nameInfo.name2 || '比对文档2';

    const loadingTask = pdfjsLib.getDocument(pdf1Url.value)
    pdf1Instance = await loadingTask.promise
    pdf1TotalPages.value = pdf1Instance.numPages
    await loadAndRenderPdf(page1.value)
    // 右侧PDF
    const loadingTask2 = pdfjsLib.getDocument(pdf2Url.value)
    pdf2Instance = await loadingTask2.promise
    pdf2TotalPages.value = pdf2Instance.numPages
    await loadAndRenderPdf2(page2.value)
    console.log('加载完成');
    loading.close()
    // 监听差异列表显示状态变化，调整缩放
    watch(showDiffList, (newVal) => {
        if (newVal) {
            // 差异列表显示时，缩小到175%
            zoomLevels.value.left = 1.0;
            zoomLevels.value.right = 1.0;
        } else {
            // 差异列表隐藏时，恢复到200%
            zoomLevels.value.left = 1.25;
            zoomLevels.value.right = 1.25;
        }
        // 重新渲染PDF
        loadAndRenderPdf(page1.value, zoomLevels.value.left);
        loadAndRenderPdf2(page2.value, zoomLevels.value.right);
    });
    
    // 修复事件监听 - 使用 setTimeout 确保DOM已渲染完成
    setTimeout(() => {
        // 使用querySelector更可靠
        const leftPdfViewer = document.querySelector('.pdf-viewer')
        const rightPdfViewer = document.querySelectorAll('.pdf-viewer')[1]
        
        // 确保元素存在再添加事件监听
        if (leftPdfViewer) {
            // 左侧PDF拖动事件
            leftPdfViewer.addEventListener('mousedown', handleMouseDown.bind(null, 1))
            leftPdfViewer.addEventListener('mousemove', handleMouseMove.bind(null, 1))
            leftPdfViewer.addEventListener('mouseup', handleMouseUp.bind(null, 1))
            leftPdfViewer.addEventListener('mouseleave', handleMouseUp.bind(null, 1))
            leftPdfViewer.addEventListener('wheel', handleWheel.bind(null, 1))
        }
        
        if (rightPdfViewer) {
            // 右侧PDF拖动事件
            rightPdfViewer.addEventListener('mousedown', handleMouseDown.bind(null, 2))
            rightPdfViewer.addEventListener('mousemove', handleMouseMove.bind(null, 2))
            rightPdfViewer.addEventListener('mouseup', handleMouseUp.bind(null, 2))
            rightPdfViewer.addEventListener('mouseleave', handleMouseUp.bind(null, 2))
            rightPdfViewer.addEventListener('wheel', handleWheel.bind(null, 2))
        }
    }, 100);
    
    // 添加滚动事件监听
    const pdfViewers = document.querySelectorAll('.pdf-viewer');
    pdfViewers.forEach(viewer => {
        viewer.addEventListener('scroll', debounce(() => {
            if (currentDiffIdx !== null) {
                highlightDiff(currentDiffIdx);
            }
        }, 16));
    });
});

onBeforeUnmount(() => {
    console.log(loading);
    loading.close()
})

// 添加防抖函数
function debounce(fn, delay) {
    let timer = null;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, delay);
    };
}

// 鼠标拖动处理函数 - 统一使用一致的方式获取PDF查看器元素
function handleMouseDown(pdfSide, e) {
    // 只有左键点击才触发拖动
    if (e.button !== 0) return;
    
    // 使用更可靠的方式获取PDF查看器元素
    const pdfViewers = document.querySelectorAll('.pdf-viewer');
    const pdfViewer = pdfSide === 1 ? pdfViewers[0] : pdfViewers[1];
    
    if (!pdfViewer) return;
    
    if (pdfSide === 1) {
        isDragging1.value = true;
        startX1.value = e.clientX;
        startY1.value = e.clientY;
        scrollLeft1.value = pdfViewer.scrollLeft;
        scrollTop1.value = pdfViewer.scrollTop;
    } else {
        isDragging2.value = true;
        startX2.value = e.clientX;
        startY2.value = e.clientY;
        scrollLeft2.value = pdfViewer.scrollLeft;
        scrollTop2.value = pdfViewer.scrollTop;
    }
    
    // 改变鼠标样式
    pdfViewer.style.cursor = 'grabbing';
    e.preventDefault();
}

function handleMouseMove(pdfSide, e) {
    if (pdfSide === 1 && !isDragging1.value) return;
    if (pdfSide === 2 && !isDragging2.value) return;
    
    // 使用更可靠的方式获取PDF查看器元素
    const pdfViewers = document.querySelectorAll('.pdf-viewer');
    const pdfViewer = pdfSide === 1 ? pdfViewers[0] : pdfViewers[1];
    
    if (!pdfViewer) return;
    
    if (pdfSide === 1) {
        const x = e.clientX;
        const y = e.clientY;
        // 直接计算差值，不使用速度因子
        const walkX = x - startX1.value;
        const walkY = y - startY1.value;
        pdfViewer.scrollLeft = scrollLeft1.value - walkX;
        pdfViewer.scrollTop = scrollTop1.value - walkY;
    } else {
        const x = e.clientX;
        const y = e.clientY;
        const walkX = x - startX2.value;
        const walkY = y - startY2.value;
        pdfViewer.scrollLeft = scrollLeft2.value - walkX;
        pdfViewer.scrollTop = scrollTop2.value - walkY;
    }
    
    e.preventDefault();
}

function handleMouseUp(pdfSide) {
    if (pdfSide === 1) {
        isDragging1.value = false;
    } else {
        isDragging2.value = false;
    }
    
    // 使用更可靠的方式获取PDF查看器元素
    const pdfViewers = document.querySelectorAll('.pdf-viewer');
    const pdfViewer = pdfSide === 1 ? pdfViewers[0] : pdfViewers[1];
    
    if (pdfViewer) {
        pdfViewer.style.cursor = 'grab';
    }
}

// 滚轮缩放处理函数 - 优化缩放逻辑，确保优先处理缩放
function handleWheel(pdfSide, e) {
    // 总是阻止默认行为，优先处理缩放
    e.preventDefault();
    
    // 获取当前页面
    const currentPage = pdfSide === 1 ? page1.value : page2.value;
    
    // 根据滚轮方向调整缩放级别
    if (e.deltaY < 0) {
        // 向上滚动，放大
        if (pdfSide === 1 && zoomLevels.value.left < maxZoom) {
            zoomLevels.value.left = Math.min(zoomLevels.value.left + zoomStep, maxZoom);
            loadAndRenderPdf(currentPage, zoomLevels.value.left);
        } else if (pdfSide === 2 && zoomLevels.value.right < maxZoom) {
            zoomLevels.value.right = Math.min(zoomLevels.value.right + zoomStep, maxZoom);
            loadAndRenderPdf2(currentPage, zoomLevels.value.right);
        }
    } else {
        // 向下滚动，缩小
        if (pdfSide === 1 && zoomLevels.value.left > minZoom) {
            zoomLevels.value.left = Math.max(zoomLevels.value.left - zoomStep, minZoom);
            loadAndRenderPdf(currentPage, zoomLevels.value.left);
        } else if (pdfSide === 2 && zoomLevels.value.right > minZoom) {
            zoomLevels.value.right = Math.max(zoomLevels.value.right - zoomStep, minZoom);
            loadAndRenderPdf2(currentPage, zoomLevels.value.right);
        }
    }
}

// 在组件卸载时移除事件监听和清理画布
onBeforeUnmount(() => {
    try {
        // 使用唯一的变量名获取PDF查看器元素
        const unmountPdfViewers = document.querySelectorAll('.pdf-viewer');
        const leftPdfViewer = unmountPdfViewers[0];
        const rightPdfViewer = unmountPdfViewers[1];
        
        // 移除左侧PDF事件监听，确保元素存在
        if (leftPdfViewer) {
            // 注意：由于使用了bind，这里无法精确移除事件监听器
            // 但我们可以尝试移除，并确保不会抛出错误
            try {
                leftPdfViewer.removeEventListener('mousedown', handleMouseDown)
                leftPdfViewer.removeEventListener('mousemove', handleMouseMove)
                leftPdfViewer.removeEventListener('mouseup', handleMouseUp)
                leftPdfViewer.removeEventListener('mouseleave', handleMouseUp)
                leftPdfViewer.removeEventListener('wheel', handleWheel)
            } catch (error) {
                console.log('移除左侧PDF事件监听器时出错:', error);
            }
        }
        
        // 移除右侧PDF事件监听，确保元素存在
        if (rightPdfViewer) {
            try {
                rightPdfViewer.removeEventListener('mousedown', handleMouseDown)
                rightPdfViewer.removeEventListener('mousemove', handleMouseMove)
                rightPdfViewer.removeEventListener('mouseup', handleMouseUp)
                rightPdfViewer.removeEventListener('mouseleave', handleMouseUp)
                rightPdfViewer.removeEventListener('wheel', handleWheel)
            } catch (error) {
                console.log('移除右侧PDF事件监听器时出错:', error);
            }
        }
        
        // 移除滚动事件监听
        const scrollPdfViewers = document.querySelectorAll('.pdf-viewer');
        scrollPdfViewers.forEach(viewer => {
            try {
                // 移除滚动事件
                viewer.removeEventListener('scroll', null);
            } catch (error) {
                console.log('移除滚动事件监听器时出错:', error);
            }
        });
        
        // 移除画布
        const lineCanvas = document.getElementById('diff-line-canvas');
        if (lineCanvas) {
            lineCanvas.remove();
        }
    } catch (error) {
        console.log('组件卸载清理时发生错误:', error);
    }
});
</script>

<style scoped>
.page-arrow-btn {
    width: 28px;
    height: 28px;
    border: 1px solid #409eff;
    color: #409eff;
}

.compare-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.compare-header {
    min-height: 57px;
    height: 57px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32px;
    background: #1B1E25;
    color: #fff;
}

.connection-controls {
    display: flex;
    align-items: center;
    margin: 0 10px;
}

.connection-control-title {
    font-size: 14px;
    margin-right: 8px;
    white-space: nowrap;
}

.connection-control-buttons {
    display: flex;
    gap: 5px;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.similarity b {
    color: #409eff;
    font-size: 14px;
}

/* 主体区域：PDF+差异列表 */
.compare-main {
    display: flex;
    flex-direction: row;
    background: #131218;
    overflow: hidden;
}

/* PDF内容区 */
.pdf-compare-content {
    flex: 1;
    display: flex;
    gap: 16px;
    padding: 16px 32px;
    transition: width 0.2s;
    min-width: 700px;
    position: relative; /* 确保翻页按钮定位正确 */
    z-index: 1;
}

.pdf-viewer {
    position: relative;
    flex: 1;
    min-width: 320px;
    background: #fff;
    border: 1.5px solid #2d2f37;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 2; /* 降低PDF层级，让翻页按钮在上 */
}

/* 自定义滚动条样式 */
.pdf-viewer::-webkit-scrollbar {
    width: 6px;
}

.pdf-viewer::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.pdf-viewer::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
}

/* 自定义滚动条样式 */
.pdf-viewer::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* 自定义滚动条样式 */
.pdf-viewer::-webkit-scrollbar {
    width: 6px;
}

/* PDF查看器拖动样式 */
.pdf-viewer {
    cursor: grab;
}

.pdf-viewer:active {
    cursor: grabbing;
}

.pdf-viewer::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.pdf-viewer::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
}

.pdf-viewer::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* 差异列表侧边栏样式 - 深色主题 */
.diff-list-sidebar {
    width: 340px;
    background: #1B1E25;
    border-left: 1px solid #2d2f37;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    height: 100%;
}

.diff-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #2d2f37;
    background: #23242a;
}

.diff-list-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
}

.diff-list-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;
    background: #1B1E25;
}

.diff-item {
    background: #2d2f37;
    border-radius: 8px;
    padding: 16px 12px;
    margin: 0 12px 12px 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    transition: all 0.3s ease;
}

.diff-item:hover {
    border: 1.5px solid #409EFF;
    transform: translateY(-1px);
}

.diff-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 8px;
    color: #fff;
}

.diff-row {
    margin-bottom: 4px;
    font-size: 12px;
    word-break: break-all;
    color: #fff;
}

.diff-label {
    color: #aaa;
    margin-right: 4px;
    font-size: 12px;
}

.text-red-500 {
    color: #ff6b6b !important;
}

.text-white {
    color: #fff !important;
}


.compare-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #1B1E25;
    border-top: 1px solid #1B1E25;
    height: 56px;
    padding: 0 32px;
    position: relative;
}

.footer-block {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
}

.footer-filename {
    color: #fff;
    font-weight: bold;
    font-size: 16px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.footer-page {
    display: inline-flex;
    align-items: center;
    background: #23242a;
    border: 1.5px solid #444;
    padding: 2px 12px;
    font-size: 14px;
    font-weight: bold;
    min-width: 48px;
    justify-content: center;
    z-index: 2;
}

.page-current {
    color: #fff;
}

.page-sep,
.page-total {
    color: #aaa;
}

.similarity-badge {
    background: #2D2F37;
    padding: 2px 10px;
    border-radius: 4px;
    margin: 0 4px;
    display: inline-block;
}

.debug-active {
    background: #67c23a !important;
    border-color: #67c23a !important;
    color: #fff !important;
}

.pdf-canvas-full {
    width: 100%;
    height: 100%;
}

.footer-page-center {
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep .el-overlay {
    background-color: transparent;
}
/* 新增样式 */
.pdf-container {
    display: flex;
    flex-direction: column;
    position: relative;
    flex: 1;
    min-width: 320px;
}

.control-panel {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 8px 12px;
    background: #2c3e50;
    border-bottom: 1px solid #34495e;
    border-radius: 8px 8px 0 0;
    gap: 10px;
}

.zoom-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.zoom-level {
    font-size: 12px;
    color: #ecf0f1;
    min-width: 40px;
    text-align: center;
    font-weight: 500;
}

.page-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.page-display {
    font-size: 12px;
    color: #ecf0f1;
    font-weight: 500;
    min-width: 50px;
    text-align: center;
}

.page-arrow-btn {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #ddd;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.page-arrow-btn:hover {
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
}

.page-arrow-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.pdf-viewer {
    position: relative;
    flex: 1;
    background: #fff;
    border: 1.5px solid #2d2f37;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: 0;
}

.zoom-controls .el-button-group {
    display: flex;
    gap: 2px;
}

.zoom-controls .el-button {
    padding: 4px 8px;
    font-size: 12px;
}
</style>
